import React, { Component } from 'react';
import {
    ActivityIndicator,
    Button,
    Dimensions,
    FlatList,
    Image,
    Text,
    TouchableOpacity,
    View,
} from 'react-native';

const { width, height } = Dimensions.get('screen');
const rpx = x => (width / 750) * x;

export default class ProductScreen extends Component {
    state = { res: null, refreshing: false, showTopBtn: false };

    getURL(pno) {
        return 'http://101.96.128.94:9999/data/product/list.php?pno=' + pno;
    }

    componentDidMount() {
        fetch(this.getURL(1))
            .then(res => res.json())
            .then(res => {
                console.log(res);

                this.setState({ res });
            });
    }

    render() {
        // 网络数据, 在使用前应该判断是否存在
        if (!this.state.res) return <View />;

        return (
            <View>
                <FlatList
                    data={this.state.res.data}
                    keyExtractor={(item, index) => index + ''}
                    renderItem={this._renderItem}
                    ItemSeparatorComponent={this._ItemSeparatorComponent}
                    onEndReachedThreshold={0.1}
                    onEndReached={this._onEndReached}
                    ListFooterComponent={this._ListFooterComponent}
                    refreshing={this.state.refreshing}
                    onRefresh={this._onRefresh}
                    ref={el => (this.fl = el)}
                    onScroll={this._onScroll}
                />
                {this.showTopBtn()}
            </View>
        );
    }

    _onScroll = event => {
        event.persist();
        console.log(event);

        const y = event.nativeEvent.contentOffset.y;

        this.setState({ showTopBtn: y > 2000 });
    };

    showTopBtn() {
        if (this.state.showTopBtn == false) return;

        return (
            <TouchableOpacity
                onPress={() => this.fl.scrollToIndex({ index: 0 })}
                style={{
                    padding: rpx(10),
                    borderRadius: rpx(3),
                    position: 'absolute',
                    bottom: rpx(60),
                    right: rpx(20),
                    backgroundColor: 'purple',
                    opacity: 0.7,
                }}>
                <Text style={{ color: 'white', fontSize: rpx(28) }}>返回</Text>
                <Text style={{ color: 'white', fontSize: rpx(28) }}>顶部</Text>
            </TouchableOpacity>
        );
    }

    _onRefresh = () => {
        this.setState({ refreshing: true });

        fetch(this.getURL(1))
            .then(res => res.json())
            .then(res => {
                console.log(res);
                this.setState({ res, refreshing: false });
            });
    };

    _ListFooterComponent = () => {
        const { pno, pageCount, data } = this.state.res;
        //达到最大页数, 显示没有更多
        if (pno == pageCount) {
            return (
                <Text
                    style={{
                        fontSize: rpx(27),
                        paddingVertical: rpx(20),
                        textAlign: 'center',
                    }}>
                    没有更多数据
                </Text>
            );
        }

        return (
            <View style={{ paddingVertical: rpx(16), alignItems: 'center' }}>
                <ActivityIndicator color="gray" size="large" />
                <Text style={{ fontSize: rpx(27) }}>加载中...</Text>
            </View>
        );
    };

    _onEndReached = () => {
        // 页数存在极限值
        const { pno, pageCount, data } = this.state.res;

        if (pno == pageCount) return;

        fetch(this.getURL(pno + 1))
            .then(res => res.json())
            .then(res => {
                console.log(res);
                // 合并新旧数据的数组
                res.data = [...data, ...res.data];

                this.setState({ res });
            });
    };

    _ItemSeparatorComponent = () => (
        <View style={{ height: rpx(1), backgroundColor: 'gray' }} />
    );

    _renderItem = ({ item }) => {
        return (
            <TouchableOpacity
                onPress={() => this.props.navigation.push('Detail', { lid: item.lid })}
                style={{
                    flexDirection: 'row',
                    backgroundColor: 'white',
                    alignItems: 'center',
                }}>
                <Image
                    style={{ width: rpx(170), height: rpx(170) }}
                    source={{ uri: 'http://101.96.128.94:9999/' + item.pic }}
                />
                <View style={{ justifyContent: 'space-around', flex: 1 }}>
                    <Text style={{ fontSize: rpx(30) }} numberOfLines={1}>
                        {item.title}
                    </Text>
                    <View style={{ height: rpx(15) }} />
                    <Text style={{ color: 'red', fontSize: rpx(32) }}>
                        单价:{item.price}
                    </Text>
                </View>
                <Button
                    onPress={() => this.props.navigation.push('Detail', { lid: item.lid })}
                    title="查看详情"
                />
            </TouchableOpacity>
        );
    };
}
